import json
import requests
import logging
from fastmcp import FastMCP

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,  # Capture detailed logs
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    handlers=[
        logging.StreamHandler(),  # Console output
        logging.FileHandler("server.log")  # Save to file
    ]
)
logger = logging.getLogger("MCP-server-fatch-fj")

mcp = FastMCP("MCP-server-fatch-fj")
# REST API 端点（替换为实际的 API 地址）
fatch_api_url = "http://59.211.3.122:8088/uploader/getTreeByFid"
fatch_file_url = "http://localhost:8080/process"
base_file_url = " http://59.211.3.122:8088"

# 从 REST API 获取 JSON 数据
def fetch_json_from_api(url,params):
    try:
        response = requests.get(url,params)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()  # 解析 JSON 数据
    except requests.exceptions.RequestException as e:
        print(f"Error fetching JSON from API: {e}")
        return []
def fetch_text_from_api(url,params):
    try:
        response = requests.get(url,params)
        response.raise_for_status()  # 检查请求是否成功
        return response.text  # 解析 JSON 数据
    except requests.exceptions.RequestException as e:
        print(f"Error fetching JSON from API: {e}")
        return []
    
# 将 JSON 转换为 Markdown 带编号的列表
def json_to_md_numbered(data):
    md_output = ""
    target_data = data[0]["children"]["children"]
    # 遍历每个目录节点
    for index, item in enumerate(target_data, start=1):
        title = item.get("title", "Unnamed")
        # 为目录生成一级编号
        md_output += f"{index}. {title}\n"
        
        # 处理文件列表
        files = item.get("files", [])
        for file_index, file in enumerate(files, start=1):
            file_title = file.get("title", "Unnamed File")
            file_url = file.get("url", "")
            # 为文件生成二级编号
            if file_url and file_url.strip():
                md_output += f"  {index}.{file_index}. [{file_title}]({file_url})\n"
            else:
                md_output += f"  {index}.{file_index}. {file_title}\n"
    
    return md_output

@mcp.tool()
def fetch_File(xmbh: int) -> str:
    params = {
            "bucket": "upload-ydk",
            "classify": "10-1",
            "fid":xmbh
        }
    data = fetch_json_from_api(fatch_api_url,params)
    logger.info(f"data result: {data}")
    # if data:
    #     # 转换为 Markdown
    #     markdown_output = json_to_md_numbered(data)
    return data
@mcp.tool()
def fetch_File_content(url: str) -> str:
    full_url = base_file_url+url
    params = {
            "pdf_url":full_url
        }
    data = fetch_text_from_api(fatch_file_url,params)
    logger.info(f"data result: {data}")
    return data
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
    """Get a personalized greeting"""
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run(transport="sse")  # SSE protocol, default port (usually 8000)